package com.aipodcast.webbackend.config;

import com.aipodcast.webbackend.entity.Users;
import com.aipodcast.webbackend.service.IUsersService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author RedStar
 * @Date 2025/09/25
 * @Description
 */
@Configuration
public class AdminInitializer implements InitializingBean {

    @Resource
    private IUsersService usersService;

    @Value("${admin.mobile}")
    private String adminMobile;

    @Value("${admin.password}")
    private String adminPassword;

    private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();


    @Override
    @Transactional
    public void afterPropertiesSet() throws Exception {
        long count = usersService.count();
        if (count == 0) {
            Users users = new Users();
            users.setId(UUID.randomUUID().toString().replace("-", ""));
            users.setMobile(adminMobile);
            users.setNickname("admin");
            users.setPasswordHash(passwordEncoder.encode(adminPassword));
            users.setRole(3);
            users.setStatus(1);
            users.setAvatarUrl("https://api.multiavatar.com/tom.png");
            users.setLastLoginIp("");
            users.setLastLoginTime(LocalDateTime.now());
            usersService.save(users);
        }
    }
}
